package com.basin.feign.util;

import com.basin.common.core.exception.BasinException;
import com.basin.feign.config.vo.FeignReqSettingsVO;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Slf4j
public final class SignUtil {
    private SignUtil() {
    }

    public static String createSignature(FeignReqSettingsVO vo) {
        try {
            String data = vo.getAppKey();
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec sks = new SecretKeySpec(vo.getSecretKey().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            mac.init(sks);
            byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hash);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            log.error("Error creating signature", e);
            throw new BasinException("Feign请求创建认证信息异常:" + e.getMessage());
        }
    }
}
